import { UserApi } from '@/api/user'
import { useUserStore } from './user'
import { clearToken, getToken, setToken } from '@/utils/auth'

export const useAuthStore = defineStore('auth', () => {
  const userStore = useUserStore()
  /**
   * 登录
   *
   * @param {LoginData}
   * @returns
   */
  function login(loginData: any) {
    return new Promise<void>((resolve, reject) => {
      UserApi.login(loginData)
        .then((res) => {
          if (res.success) {
            const token = res.item?.token
            const userInfo = res.item?.userInfo
            console.log(userInfo)

            setToken(token!)
            userStore.setUserInfo(userInfo ?? {})
          }
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  async function logout() {
    return new Promise<void>((resolve) => {
      UserApi.logout().then(() => {
        clearToken()
        userStore.setUserInfo(undefined)
        resolve()
      })
    })
  }

  function register(registerData: any) {
    return new Promise<void>((resolve) => {
      UserApi.register(registerData).then(() => {
        resolve()
      })
    })
  }

  const isAuthenticated = computed(async () => {
    const token = getToken()
    // debugger
    if (token.trim().length !== 0) {
      if (userStore.userInfo == undefined) {
        try {
          const res = await userStore.toGetUserInfo()
          if (res != undefined) {
            return Promise.resolve(true)
          }
        } catch (error) {
          return Promise.reject(error)
        }
      }
      return Promise.resolve(true)
    }
    return Promise.resolve(false)
  })

  return {
    login,
    logout,
    register,
    isAuthenticated,
  }
})
